﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Reflection;
using MAPIdotnet;
using Microsoft.WindowsMobile.PocketOutlook;
namespace SMSRulez
{
    public class HiddenFolderClass
    {
        private MAPI mapi;
        private IMAPIMsgStore[] stores;
        IMAPIFolder restorationFolder = null;
        OutlookSession myOutlook = new OutlookSession();
        SmsAccount SMS = null;
        const string hiddenFolderName = "secret";
        string smsName = string.Empty;
        static string location = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
        DataTable tableRule;
        bool passwordCheck = false;
        DB db;
        public HiddenFolderClass(string password)
        {
            tableRule = new DataTable();
            db = new DB(location);
            passwordCheck = CheckPassword(password);
            mapi = new MAPI();
            stores = mapi.MessageStores;
            SMS = myOutlook.SmsAccount;
            smsName = SMS.Name.Trim().ToUpper();
        }
        public HiddenFolderClass()
        {
            passwordCheck = false;
            mapi = new MAPI();
            stores = mapi.MessageStores;
            SMS = myOutlook.SmsAccount;
            smsName = SMS.Name.Trim().ToUpper();
        }

        private IMAPIMsgStore ReturnSMSStore()
        {
            for (int i = 0, length = stores.Length; i < length; i++)
            {
                IMAPIMsgStore store = stores[i];
                IMAPIFolder topFolder = store.RootFolder.OpenFolder().ParentFolder.OpenFolder();
                if (string.Compare(store.DisplayName.ToUpper(), smsName, StringComparison.OrdinalIgnoreCase | StringComparison.Ordinal) == 0)
                {
                    return store;
                }
            }
            return null;
        }
        /// <summary>
        /// Use to create hiddenFolder to store private messages
        /// </summary>
        /// <returns>IMAPIFolder type hiddenFolder  </returns>
        public IMAPIFolder CreateHiddenFolder()
        {
            IMAPIFolder hiddenFolder = null;
            IMAPIMsgStore store = ReturnSMSStore();
            IMAPIFolder topFolder = store.RootFolder.OpenFolder().ParentFolder.OpenFolder();
            hiddenFolder = null;
            if (store != null)
            {
                if (hiddenFolder == null)
                {
                    hiddenFolder = topFolder.CreateFolder(hiddenFolderName, true);
                }
            }
            return hiddenFolder;
        }
        /// <summary> 
        /// Makes PRIVATE folder visible in SMS folders
        /// </summary> 
        private void OpenOrCreatePrivateFolder()
        {
            IMAPIMsgStore store = ReturnSMSStore();
            IMAPIFolder topFolder = store.RootFolder.OpenFolder();
            restorationFolder = topFolder.CreateFolder("PRIVATE", true);
        }
        /// <summary>
        /// Deletes the PRIVATE folder and the messages
        /// </summary>
        private void DeletePrivateFolder()
        {
            OpenOrCreatePrivateFolder();
            restorationFolder.EmptyFolder();
            restorationFolder.DeleteFolder(restorationFolder.FolderID, true, true);
            IMAPIMsgStore store = ReturnSMSStore();
            IMAPIFolder trash = store.TrashFolder.OpenFolder();
            trash.EmptyFolder();

        }
        /// <summary>
        /// Copies the private messages from Hidden folder to the PRIVATE folder
        /// </summary>
        public void MoveMessagesFromHiddenFolderToPrivateFolder()
        {
            if (passwordCheck)
            {
                OpenOrCreatePrivateFolder();
                IMAPIFolder hiddenFolder = CreateHiddenFolder();
                MoveMessages(hiddenFolder, restorationFolder);
            }
        }


        /// <summary>
        /// Hides the PRIVATE folder and copy the messages back to the hidden folder
        /// </summary>
        public void HideMessageFromPrivateFolder()
        {
            OpenOrCreatePrivateFolder();
            IMAPIFolder hiddenFolder = CreateHiddenFolder();
            MoveMessages(restorationFolder, hiddenFolder);
            DeletePrivateFolder();
        }
        /// <summary>
        /// deletes all the private messages
        /// </summary>
        public void DeleteAllPrivateMessages()
        {
            MoveMessagesFromHiddenFolderToPrivateFolder();
            DeletePrivateFolder();
        }

        public IMAPIMessageID[] GetMessagesFromFolders(IMAPIFolder folder)
        {
            IMAPIFolder sortedFolder = folder;
            sortedFolder.SortMessagesByDeliveryTime(TableSortOrder.TABLE_SORT_DESCEND);
            List<IMAPIMessage> folderMessages = new List<IMAPIMessage>();// folder.GetNextMessages(folder.NumSubItems);
            for (int pos = 0; pos < sortedFolder.NumSubItems; pos++)
            {
                try
                {
                    //sortedFolder.SeekMessages(pos);
                    folderMessages.Add((IMAPIMessage)sortedFolder.GetNextMessages(1).GetValue(0));
                }
                catch (Exception ex)
                {
                }
            }

            List<IMAPIMessageID> messages = new List<IMAPIMessageID>();
            for (int i = 0, length = folderMessages.Count; i < length; i++)
            {
                IMAPIMessage msg = folderMessages[i];
                messages.Add(msg.MessageID);
            }
            return messages.ToArray();
        }

        /// <summary> 
        /// Method to copy message from one folder to another
        /// </summary> 
        /// <param name="sourceFolder"></param> 
        /// <param name="destinationFolder"></param> 
        private void MoveMessages(IMAPIFolder sourceFolder, IMAPIFolder destinationFolder)
        {
            IMAPIMessageID[] allMessages = GetMessagesFromFolders(sourceFolder);
            List<IMAPIMessageID> message = new List<IMAPIMessageID>();
            foreach (IMAPIMessageID eachMessage in allMessages)
            {
                message.Clear();
                message.Add(eachMessage);
                sourceFolder.CopyMessages(message.ToArray(), destinationFolder, true);
            }
        }

        #region Overloaded
        private void MoveMessages(IMAPIFolder sourceFolder, IMAPIFolder destinationFolder, int messageCount)
        {
            IMAPIMessageID[] allMessages = GetMessagesFromFolders(sourceFolder, messageCount);
            List<IMAPIMessageID> message = new List<IMAPIMessageID>();
            foreach (IMAPIMessageID eachMessage in allMessages)
            {
                message.Clear();
                message.Add(eachMessage);
                sourceFolder.CopyMessages(message.ToArray(), destinationFolder, true);
            }
        }

        public void MoveMessagesFromHiddenFolderToPrivateFolder(int messageCount)
        {
            if (passwordCheck)
            {
                OpenOrCreatePrivateFolder();
                IMAPIFolder hiddenFolder = CreateHiddenFolder();
                MoveMessages(hiddenFolder, restorationFolder, messageCount);
            }
        }

        public IMAPIMessageID[] GetMessagesFromFolders(IMAPIFolder folder, int messageCount)
        {
            IMAPIFolder sortedFolder = folder;

            List<IMAPIMessage> folderMessages= new List<IMAPIMessage>();
            sortedFolder.SortMessagesByDeliveryTime(TableSortOrder.TABLE_SORT_DESCEND);
            if (messageCount == int.MaxValue)
            {
                int pos = 0;

                for (pos = 0; pos < sortedFolder.NumSubItems; pos++)
                {
                    try
                    {
                        //sortedFolder.SeekMessages(pos);
                        folderMessages.Add((IMAPIMessage)sortedFolder.GetNextMessages(1).GetValue(0));
                    }
                    catch (Exception ex)
                    {
                    }
                }
                
                   
            }
            else
            {
                //folderMessages = folder.GetNextMessages(messageCount);
                int pos = 0;

                for (pos = 0; pos < messageCount; pos++)
                {
                    try
                    {
                        //sortedFolder.SeekMessages(pos);
                        folderMessages.Add((IMAPIMessage)sortedFolder.GetNextMessages(1).GetValue(0));
                    }
                    catch
                    {
                    }
                }
                
            }
            List<IMAPIMessageID> messages = new List<IMAPIMessageID>();
            for (int i = 0, length = folderMessages.Count; i < length; i++)
            {
                IMAPIMessage msg = folderMessages[i];
                messages.Add(msg.MessageID);
            }
            return messages.ToArray();
        }

        #endregion Overloaded

        private bool CheckPassword(string password)
        {
            string command = "SELECT * FROM Password WHERE password = '" + password.Trim() + "'"; //Check password from database
            db.SetConnection(command, DB.sqlAction.Select, out tableRule);
            if (tableRule.Rows.Count < 1)
            {
                return false;
            }
            else
            {
                return true;
            }
        }


    }
}
